import router from './index'
import { useAuthStore } from '../store/auth'
import { storeToRefs } from 'pinia'

const getSubRouters = (url: string, list: any) => {

    let _list: any = [];
    list.forEach((item: any) => {

        _list.push({
            path: `${url}/${item.url}`,
            name: item.pathName + item.id,
            component: () => import(`../views/${url}/${item.url}/${item.pathName}View.vue`)
        });

        if (item.children?.length > 0) {
            let childs = getSubRouters(url + "/" + item.url, item.children);
            _list = [..._list, ...childs]
        }




    });

    return _list;


}

const getCareRoutes = () => {

    const authStore = useAuthStore();
    const { menus } = storeToRefs(authStore);
    let _arrRouters: any = [];
    menus.value.forEach((item: any) => {
        let _list = getSubRouters(item.url, item.children);
        _arrRouters = _arrRouters.concat(_list);

    })

    let careRoute = {
        path: "/",
        name: "Home",
        component: () => import("../views/Home.vue"),
        children: _arrRouters
    }

    return careRoute;

}

//路由前置守卫  、、页面访问控制   动态路由实现
router.beforeEach((to: any) => {


    const authStore = useAuthStore();
    const { token } = storeToRefs(authStore);
    if (to.path != "/login") {
 
        if (!token.value) {
 
            return "/login"
        }
        else{

           let len=router.getRoutes().length;
            if(len<3){
                let _router=getCareRoutes();
                router.addRoute(_router);
                
             return to.fullPath;
            }

        }

    }

 




})